'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  Box,
  Container,
  Typography,
  Paper,
  TextField,
  Button,
  Alert,
  CircularProgress,
  Divider,
  Grid,
  Card,
  CardContent,
  CardActions,
  Breadcrumbs,
} from '@mui/material';
import Navbar from '@/components/Navbar';

export default function CompanyManagePage() {
  const router = useRouter();
  const [user, setUser] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [companyInfo, setCompanyInfo] = useState<any>(null);
  const [formData, setFormData] = useState({
    company_name: '',
    company_role: '管理员',
  });

  useEffect(() => {
    const fetchUserProfile = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          router.push('/auth/login');
          return;
        }

        const response = await fetch('/api/profile', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (!response.ok) {
          throw new Error('获取用户资料失败');
        }

        const userData = await response.json();
        setUser(userData);

        // 如果用户已经是企业管理员，获取企业信息
        if (userData.is_company_admin) {
          try {
            const companyResponse = await fetch('/api/company/info', {
              headers: {
                Authorization: `Bearer ${token}`,
              },
            });

            if (companyResponse.ok) {
              const companyData = await companyResponse.json();
              setCompanyInfo(companyData);
            }
          } catch (companyError) {
            console.error('获取企业信息失败:', companyError);
          }
        }

        // 预填充表单
        if (userData.company) {
          setFormData(prev => ({
            ...prev,
            company_name: userData.company,
          }));
        }
      } catch (err) {
        setError((err as Error).message);
      } finally {
        setLoading(false);
      }
    };

    fetchUserProfile();
  }, [router]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSetCompanyAdmin = async () => {
    try {
      setLoading(true);
      setError('');
      setSuccess('');

      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/auth/login');
        return;
      }

      const response = await fetch('/api/profile/set-company-admin', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '设置企业管理员失败');
      }

      setSuccess('设置企业管理员成功');
      setUser(data.user);

      // 获取企业信息
      try {
        const companyResponse = await fetch('/api/company/info', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (companyResponse.ok) {
          const companyData = await companyResponse.json();
          setCompanyInfo(companyData);
        }
      } catch (companyError) {
        console.error('获取企业信息失败:', companyError);
      }
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  if (loading && !user) {
    return (
      <>
        <Navbar />
        <Container maxWidth="lg" sx={{ py: 8, textAlign: 'center' }}>
          <CircularProgress />
          <Typography variant="h6" sx={{ mt: 2 }}>
            正在加载...
          </Typography>
        </Container>
      </>
    );
  }

  return (
    <>
      <Navbar />
      <Box sx={{ bgcolor: 'background.default', minHeight: '100vh', py: 4 }}>
        <Container maxWidth="lg">
          <Box sx={{ mb: 4 }}>
            <Breadcrumbs aria-label="breadcrumb">
              <Link href="/" passHref>
                <Typography color="inherit">首页</Typography>
              </Link>
              <Typography color="text.primary">企业管理</Typography>
            </Breadcrumbs>
          </Box>

          <Typography variant="h4" component="h1" gutterBottom>
            企业管理
          </Typography>

          {error && (
            <Alert severity="error" sx={{ mb: 3 }}>
              {error}
            </Alert>
          )}

          {success && (
            <Alert severity="success" sx={{ mb: 3 }}>
              {success}
            </Alert>
          )}

          <Grid container spacing={3}>
            <Grid item xs={12} md={6}>
              <Paper sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                  {user?.is_company_admin ? '更新企业信息' : '设置为企业管理员'}
                </Typography>
                <Typography variant="body2" color="text.secondary" paragraph>
                  {user?.is_company_admin
                    ? '您已是企业管理员，可以更新企业信息'
                    : '设置为企业管理员后，您可以发布招聘信息和管理企业资料'}
                </Typography>

                <TextField
                  fullWidth
                  label="企业名称"
                  name="company_name"
                  value={formData.company_name}
                  onChange={handleChange}
                  margin="normal"
                  required
                />

                <TextField
                  fullWidth
                  label="您在企业中的角色"
                  name="company_role"
                  value={formData.company_role}
                  onChange={handleChange}
                  margin="normal"
                  placeholder="如：HR经理、招聘主管等"
                />

                <Button
                  variant="contained"
                  color="primary"
                  onClick={handleSetCompanyAdmin}
                  disabled={loading || !formData.company_name}
                  sx={{ mt: 3 }}
                >
                  {loading ? (
                    <CircularProgress size={24} />
                  ) : user?.is_company_admin ? (
                    '更新企业信息'
                  ) : (
                    '设置为企业管理员'
                  )}
                </Button>
              </Paper>
            </Grid>

            <Grid item xs={12} md={6}>
              {user?.is_company_admin && companyInfo && (
                <Paper sx={{ p: 3 }}>
                  <Typography variant="h6" gutterBottom>
                    企业信息
                  </Typography>
                  <Box sx={{ mb: 2 }}>
                    <Typography variant="subtitle2" color="text.secondary">
                      企业名称
                    </Typography>
                    <Typography variant="body1">{companyInfo.name}</Typography>
                  </Box>

                  <Divider sx={{ my: 2 }} />

                  <Typography variant="h6" gutterBottom>
                    企业功能
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={12} sm={6}>
                      <Card>
                        <CardContent>
                          <Typography variant="h6" component="div">
                            发布招聘
                          </Typography>
                          <Typography variant="body2" color="text.secondary">
                            发布新的招聘信息
                          </Typography>
                        </CardContent>
                        <CardActions>
                          <Button
                            size="small"
                            color="primary"
                            onClick={() => router.push('/recruitment/post')}
                          >
                            立即发布
                          </Button>
                        </CardActions>
                      </Card>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <Card>
                        <CardContent>
                          <Typography variant="h6" component="div">
                            管理招聘
                          </Typography>
                          <Typography variant="body2" color="text.secondary">
                            查看和管理已发布的招聘信息
                          </Typography>
                        </CardContent>
                        <CardActions>
                          <Button
                            size="small"
                            color="primary"
                            onClick={() => router.push('/recruitment/manage')}
                          >
                            查看管理
                          </Button>
                        </CardActions>
                      </Card>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <Card>
                        <CardContent>
                          <Typography variant="h6" component="div">
                            简历管理
                          </Typography>
                          <Typography variant="body2" color="text.secondary">
                            查看收到的简历
                          </Typography>
                        </CardContent>
                        <CardActions>
                          <Button
                            size="small"
                            color="primary"
                            onClick={() => router.push('/recruitment/resumes')}
                          >
                            查看简历
                          </Button>
                        </CardActions>
                      </Card>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <Card>
                        <CardContent>
                          <Typography variant="h6" component="div">
                            企业资料
                          </Typography>
                          <Typography variant="body2" color="text.secondary">
                            完善企业详细资料
                          </Typography>
                        </CardContent>
                        <CardActions>
                          <Button
                            size="small"
                            color="primary"
                            onClick={() => router.push('/company/profile')}
                          >
                            编辑资料
                          </Button>
                        </CardActions>
                      </Card>
                    </Grid>
                  </Grid>
                </Paper>
              )}

              {user?.is_company_admin && !companyInfo && (
                <Paper sx={{ p: 3, textAlign: 'center' }}>
                  <CircularProgress size={30} />
                  <Typography variant="body1" sx={{ mt: 2 }}>
                    正在加载企业信息...
                  </Typography>
                </Paper>
              )}

              {!user?.is_company_admin && (
                <Paper sx={{ p: 3 }}>
                  <Typography variant="h6" gutterBottom>
                    企业管理员权限
                  </Typography>
                  <Typography variant="body1" paragraph>
                    成为企业管理员后，您将获得以下权限：
                  </Typography>
                  <ul>
                    <li>
                      <Typography variant="body1">发布企业招聘信息</Typography>
                    </li>
                    <li>
                      <Typography variant="body1">管理企业资料</Typography>
                    </li>
                    <li>
                      <Typography variant="body1">查看收到的简历</Typography>
                    </li>
                    <li>
                      <Typography variant="body1">与求职者沟通</Typography>
                    </li>
                  </ul>
                </Paper>
              )}
            </Grid>
          </Grid>
        </Container>
      </Box>
    </>
  );
}
